/**
 * LinkedLST
 * May 11, 2011
 * HomeView.java - Home activity
 */

package edu.washington.cs.labspecimentransport;
import edu.washington.cs.labspecimentransport.data.DataQuery;
import edu.washington.cs.labspecimentransport.ops.CommonHandlers;
import edu.washington.cs.labspecimentransport.ops.Keys;
import edu.washington.cs.labspecimentransport.ops.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * HomeView displays the home screen of the Lab Specimen Transport application, which
 * provides navigation to the Checklist, Lookup, Pickup Locations, and 
 * Dropoff Locations screens. Users are also able to logout from here.
 * 
 * <p>
 * An intent with the following key is expected:
 * 	int : KEY_COURIERID - the courier id
 * 	boolean : KEY_CHECKLIST_AFTER - if the after checklist is finished
 * 	boolean : KEY_CHECKLIST_BEFORE - if the before checklist is finished
 */
public class HomeView extends Activity {
	private int courierid;				// the id of the courier logged in
	private Bundle courierInfoBundle;	// pointer to intent bundle
	private DataQuery dq;

	private Button checklist_button;
	private Button lookup_button;
	private Button locations_button;
	private Button logout_button;
	
	private boolean checklist_afterDone;
	private boolean checklist_beforeDone;
	
	// flag for whether or not activity initialization has occurred
	private boolean firstExecution;		

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        firstExecution = true;
        
        // lock the screen in portrait orientation
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    	dq = DataQuery.getInstance();
        
    	setupButtons(); 	// setup the 5 buttons
    	refresh(); 			// do a check of the checklist
    	refreshButtons(); 	// set which buttons should be enabled or disabled
    }
    
    /**
     * Push the activity to the back when back button is pressed,
     * rather than going back to the login page
     */
    public void onBackPressed() {
    	moveTaskToBack(true);
    }
    
    /**
     * Define the options menu.
     */
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, Keys.MENUID_REFRESH, 0, R.string.option_refresh);
    	menu.add(0, Keys.MENUID_HELP, 0, R.string.option_help);
    	return true;
    }

    /**
     * Define functionality for each item in options menu.
     */
    public boolean onOptionsItemSelected(MenuItem item) {   
        switch(item.getItemId()) {
        case Keys.MENUID_REFRESH:
        	refresh();
        	break;
        case Keys.MENUID_HELP:
        	CommonHandlers.startHelp(this);
        	break;
        default:
        	super.onOptionsItemSelected(item);
        	break;
        }
        
        return true;
    }
    
	/**
	 * Update button states on return from ChecklistView.
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0 && resultCode == RESULT_OK) {
			checklist_beforeDone = data.getExtras().getBoolean(Keys.KEY_CHECKLIST_BEFORE);
    		checklist_afterDone = data.getExtras().getBoolean(Keys.KEY_CHECKLIST_AFTER);
    		refreshButtons();
		}
	}
    
    /**
     * Extract required information from intent
     */
    private void getPassedData() {
    	courierInfoBundle = getIntent().getExtras();
    	courierid = courierInfoBundle.getInt(Keys.KEY_COURIERID);
    	checklist_beforeDone = courierInfoBundle.getBoolean(Keys.KEY_CHECKLIST_BEFORE);
    	checklist_afterDone = courierInfoBundle.getBoolean(Keys.KEY_CHECKLIST_AFTER);
    }
    
    /**
     * Refresh the page by checking whether the checklist is
     * completed
     */
    private void refresh() {
    	dq.flushEntireCache();
    	new UpdateChecklist().execute();
    }
    
    /**
     * Set which buttons should be enabled or disabled, according
     * to the status of the checklist
     */
    private void refreshButtons() {
    	lookup_button.setEnabled(checklist_beforeDone);
    	locations_button.setEnabled(checklist_beforeDone);
    	//logout_button.setEnabled(checklist_afterDone);
    	
    	if (Settings.testMode) {
        	lookup_button.setEnabled(true);
        	locations_button.setEnabled(true);
        	//logout_button.setEnabled(true);
    	}
    }
    
    /**
     * Sets up all the buttons on the screen
     */
    private void setupButtons() {
    	// "Refresh" menu button
    	Button r = (Button) findViewById(R.id.refresh_button);
    	r.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				refresh();
			}
    	});
    	
    	// "Checklist" button
    	checklist_button = (Button) findViewById(R.id.checklist_button);
    	checklist_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(HomeView.this, ChecklistView.class);
				Bundle b = new Bundle();
				b.putAll(getIntent().getExtras());
				b.putBoolean(Keys.KEY_CHECKLIST_BEFORE, checklist_beforeDone);
				b.putBoolean(Keys.KEY_CHECKLIST_AFTER, checklist_afterDone);
				i.putExtras(b);
				
				startActivityForResult(i, 0);
			}
    	});

    	// "Lookup" button
    	lookup_button = (Button) findViewById(R.id.lookup_button);
    	lookup_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(HomeView.this, BarcodeLookupView.class);
				Bundle b = new Bundle();
				b.putAll(getIntent().getExtras());
				b.putBoolean(Keys.KEY_CHECKLIST_BEFORE, checklist_beforeDone);
				b.putBoolean(Keys.KEY_CHECKLIST_AFTER, checklist_afterDone);
				i.putExtras(b);
				startActivity(i);
			}
    	});
    	
    	// "Pickup" button
    	locations_button = (Button) findViewById(R.id.locations_button);
    	locations_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(HomeView.this, LocationsView.class);
				Bundle b = new Bundle();
				b.putAll(courierInfoBundle);
				b.putBoolean(Keys.KEY_CHECKLIST_BEFORE, checklist_beforeDone);
				b.putBoolean(Keys.KEY_CHECKLIST_AFTER, checklist_afterDone);
				i.putExtras(b);
				startActivity(i);
			}
    	});
    	
    	// "Logout" button
    	logout_button = (Button) findViewById(R.id.logout_button);
    	logout_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (!checklist_afterDone) {
					// display an alert dialog asking for confirmation if 
					// after checklist is not completed
					AlertDialog.Builder builder = new AlertDialog.Builder(HomeView.this);
					builder.setMessage(getString(R.string.home_dialog_logout));
					builder.setCancelable(true);

					builder.setPositiveButton(getString(R.string.dialog_yes), 
							new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {	
							Intent i = new Intent(HomeView.this, LoginView.class);
							startActivity(i);
							finish();
						}
					});

					builder.setNegativeButton(getString(R.string.dialog_cancel), 
							new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
					AlertDialog alert = builder.create();
					alert.show();
				} else {
					Intent i = new Intent(HomeView.this, LoginView.class);
					startActivity(i);
					finish();
				}
			}
    	});
    }
    
    /**
     * Service to check whether or not checklist has been completed.
     */
	private class UpdateChecklist extends AsyncTask<Void, Void, Void> {
		private ProgressDialog dialog;
		private boolean success;
		
		// before execution
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			success = true;
			dialog = ProgressDialog.show(HomeView.this, "", 
					getString(R.string.home_load), true, true,
					new DialogInterface.OnCancelListener(){
				public void onCancel(DialogInterface dialog) {
					UpdateChecklist.this.cancel(true);
					onBackPressed();
				}
			});
		}
		
		// execution
		@Override
		protected Void doInBackground(Void... unused) {
			try {
				if (firstExecution) {
					getPassedData();
					firstExecution = false;
				}
			} catch (NullPointerException e) {
				success = false;
			}
			return null;
		}

		// after execution
		@Override
		protected void onPostExecute(Void unused) {
			dialog.dismiss();
			if (success) {
				refreshButtons();
			} else {
				Toast toast = Toast.makeText(HomeView.this, 
						R.string.error_default, Toast.LENGTH_LONG);
				toast.show();
			}
		}
	}  	
}